document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const alertBox = document.querySelector('.alert');

    // 表单验证
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('登录表单提交');
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const role = document.getElementById('role').value;
        
        if (!username || !password || !role) {
            showAlert('请填写所有必填字段！', 'danger');
            return;
        }

        // 打印登录信息（仅用于调试）
        console.log('登录信息：', {
            username: username,
            password: password,
            role: role
        });
        
        // 调用后端登录API
        showAlert('登录验证中...', 'info');
        
        fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password,
                role: role.toUpperCase()  // 转换为大写以匹配数据库中的枚举值
            })
        })
        .then(response => {
            console.log('服务器响应状态：', response.status);
            return response.json().catch(error => {
                console.error('解析响应JSON失败：', error);
                throw new Error('服务器响应格式错误');
            });
        })
        .then(data => {
            console.log('服务器响应数据：', data);
            if (data.success) {
                showAlert('登录成功！即将跳转...', 'success');
                // 存储用户信息
                localStorage.setItem('userId', data.userId);
                localStorage.setItem('username', data.username);
                localStorage.setItem('role', data.role);
                if (data.token) {
                    localStorage.setItem('token', data.token);
                }
                
                // 根据角色跳转到不同页面
                setTimeout(() => {
                    switch(data.role) {
                        case 'ADMIN':
                            window.location.href = '/admin/dashboard.html';
                            break;
                        case 'METER_READER':
                            window.location.href = '/meter-reader/dashboard.html';
                            break;
                        case 'CUSTOMER':
                            window.location.href = '/customer/dashboard.html';
                            break;
                        default:
                            window.location.href = '/login.html';
                            showAlert('未知的用户角色！', 'danger');
                    }
                }, 1000);
            } else {
                showAlert(data.message || '登录失败！', 'danger');
            }
        })
        .catch(error => {
            console.error('登录请求失败：', error);
            showAlert('登录失败，请稍后重试！', 'danger');
        });
    });
    
    // 密码显示切换
    const togglePassword = document.querySelector('.toggle-password');
    const passwordInput = document.getElementById('password');
    
    if (togglePassword) {
        togglePassword.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            this.classList.toggle('fa-eye');
            this.classList.toggle('fa-eye-slash');
        });
    }
    
    // 角色选择变化时更新图标
    const roleSelect = document.getElementById('role');
    const roleIcon = document.querySelector('.role-icon');
    
    roleSelect.addEventListener('change', function() {
        const role = this.value;
        switch(role) {
            case 'ADMIN':
                roleIcon.className = 'fas fa-user-shield role-icon';
                break;
            case 'METER_READER':
                roleIcon.className = 'fas fa-clipboard-list role-icon';
                break;
            case 'CUSTOMER':
                roleIcon.className = 'fas fa-user role-icon';
                break;
            default:
                roleIcon.className = 'fas fa-user role-icon';
        }
    });

    // 处理从注册页面返回的状态
    const urlParams = new URLSearchParams(window.location.search);
    const registerSuccess = urlParams.get('registerSuccess');
    if (registerSuccess === 'true') {
        showAlert('注册成功！请使用新账号登录', 'success');
    }
});

// 显示提示信息
function showAlert(message, type) {
    const alertBox = document.querySelector('.alert');
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type} animated fadeIn`;
    alertBox.style.display = 'block';
    
    if (type === 'success' || type === 'danger') {
        setTimeout(() => {
            alertBox.style.display = 'none';
        }, 3000);
    }
}

// 添加输入框动画效果
document.querySelectorAll('.form-control').forEach(input => {
    input.addEventListener('focus', function() {
        this.parentElement.classList.add('input-group-focus');
    });
    
    input.addEventListener('blur', function() {
        this.parentElement.classList.remove('input-group-focus');
    });
}); 